#include "client.h"

#define CURRENT_DIR "test/"

void write_file(char *buffer, int sock, struct sockaddr *ssock, unsigned int msglength)
{
  char *file  = NULL;
  char *filename  = NULL;
  FILE *f = NULL;
  int len = sizeof(ssock);
  unsigned int fs_sz;

  filename = strdup(buffer);
  fs_sz = msglength - strlen(filename) - 1;
  file = buffer + strlen(filename) + 1;

  filename = strcat(strcat(calloc(1024, 1), CURRENT_DIR), filename);
  printf("Writing file: <%s>\n", filename);

  if ((f = fopen(filename, "w+")) == NULL)
    {
      printf("Cannot write file\n");
      perror("fopen");
      return;
    }
  fwrite(file, 1, fs_sz, f);

  fflush(f);
  fclose(f);
}

void perform_check()
{
  char* md5checker = malloc(1024);

  printf("Performing signature check...\n");
  sprintf(md5checker, "md5sum -c %s/*.md5", CURRENT_DIR);
  system(md5checker);
  free(md5checker);
  printf("signature check done\n");
}

void client_unicast(char *DestIp, int DestPort)
{
  struct sockaddr_in fsock = {0};
  int sockfd;
  char *buffer;
  char *cmp = malloc(2 * sizeof(char));

  if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) == -1)
    {
      printf("Echec creation socket()");
      return;
    }

  // sock = malloc(sizeof(struct sockaddr_in));
  fsock.sin_addr.s_addr = inet_addr(DestIp);
  fsock.sin_family = AF_INET;
  fsock.sin_port = htons(DestPort);

  if(connect(sockfd, (struct sockaddr *) &fsock, sizeof(fsock)) != -1)
    {
      printf("connected\n");
      unsigned int len = sizeof(fsock);
      unsigned int msglength;

      while(1)
        {
          buffer = calloc(100000000, 1);
          int i = 0;
          if ((msglength = recvfrom(sockfd, buffer, 100000000, 0, (struct sockaddr *) &fsock, &len)) != -1)
            {
              printf("received %d bytes.\n", msglength);
              if (strcmp(buffer, "SEND") == 0)
                write_file(buffer + 5, sockfd, (struct sockaddr *) &fsock, msglength - 5);
              else if (strcmp(buffer, "SELFCHECK") == 0)
                perform_check();
              else
                //printf("unknow command ");//%10s\n", buffer);
                printf("unknow command %10s\n", buffer);
            }
          else
            {
              perror("recv");
              printf("error");
              while(1);
            }
        }
    }
  else
    {
      perror("accept");
      printf("Connection impossible\n");
    }

  close(sockfd);
}

int main(int argc, char** argv)
{
  unsigned int port;

  if (argc < 2)
    {
      printf("Usage: %s port\n", argv[0]);
      return 1;
    }
  port = atoi(argv[1]);

  client_unicast("10.41.130.81", port);
  return 0;
}
